package com.example.administrator.jim.loginandregist;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.jim.MainActivity;
import com.example.administrator.jim.R;
import com.example.administrator.jim.addresslist.AddressListView;
import com.example.administrator.jim.bean.YiDengUserInfioBean;
import com.example.administrator.jim.utils.SPUtil;
import com.google.gson.jpush.Gson;
import com.isnc.facesdk.SuperID;
import com.isnc.facesdk.common.Cache;
import com.isnc.facesdk.common.SDKConfig;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sdsmdg.tastytoast.TastyToast;

import net.lemonsoft.lemonbubble.LemonBubble;
import net.lemonsoft.lemonbubble.enums.LemonBubbleLayoutStyle;
import net.lemonsoft.lemonbubble.enums.LemonBubbleLocationStyle;
import net.lemonsoft.lemonhello.LemonHello;
import net.lemonsoft.lemonhello.LemonHelloAction;
import net.lemonsoft.lemonhello.LemonHelloInfo;
import net.lemonsoft.lemonhello.LemonHelloView;
import net.lemonsoft.lemonhello.interfaces.LemonHelloActionDelegate;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.options.RegisterOptionalUserInfo;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import mehdi.sakout.fancybuttons.FancyButton;

/**
 * Created by Administrator on 2017/12/15 0015.
 * Date 2017/12/15 0015
 */

public class LoginActvity extends AppCompatActivity {
    @BindView(R.id.loginactivity_Editext_username)
    MaterialEditText mMaterialEditText_username;
    @BindView(R.id.loginactivity_Editext_userpass)
    MaterialEditText mMaterialEditText_userpass;
    @BindView(R.id.loginactivity_Button_login)
    FancyButton mFancyButton_login;
    @BindView(R.id.loginactivity_TextVieww_regist)
    TextView mTextView_regist;
    @BindView(R.id.loginactivity_ImageView_username_delete)
    ImageView mImageView_delete_username;
    @BindView(R.id.loginactivity_ImageView_yideng)
    ImageView mLoginactivityImageViewYideng;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        getSupportActionBar().hide();
        initDatas();
        initListener();
    }

    private void initListener() {
        mMaterialEditText_username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mImageView_delete_username.setVisibility(View.VISIBLE);
                } else {
                    mImageView_delete_username.setVisibility(View.GONE);
                }
            }
        });
        mImageView_delete_username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMaterialEditText_username.setText("");
            }
        });
    }

    @Override
    public void onBackPressed() {
        LemonHello.getInformationHello("您确定要退出吗？", "")
                .addAction(new LemonHelloAction("取消", new LemonHelloActionDelegate() {
                    @Override
                    public void onClick(LemonHelloView helloView, LemonHelloInfo helloInfo, LemonHelloAction helloAction) {
                        helloView.hide();
                    }
                }))
                .addAction(new LemonHelloAction("退出", Color.RED, new LemonHelloActionDelegate() {
                    @Override
                    public void onClick(LemonHelloView helloView, LemonHelloInfo helloInfo, LemonHelloAction helloAction) {
                        helloView.hide();
                        finish();
                    }
                }))
                .show(this);
    }

    private void initDatas() {
        //加载用户名
        String uname = (String) SPUtil.getValue(getApplicationContext(), SPUtil.LOGIN_USERNAME, SPUtil.SPUtil_STRING, "");
        mMaterialEditText_username.setText(uname);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(AddressListView.contacts!=null){
            AddressListView.contacts.clear();
        }
        if(AddressListView.mdatas!=null){
            AddressListView.mdatas.clear();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case SDKConfig.LOGINSUCCESS:
                LemonBubble.getRoundProgressBubbleInfo()
                        .setLocationStyle(LemonBubbleLocationStyle.BOTTOM)
                        .setLayoutStyle(LemonBubbleLayoutStyle.ICON_LEFT_TITLE_RIGHT)
                        .setBubbleSize(200, 50)
                        .setProportionOfDeviation(0.1f)
                        .setTitle("正在授权...")
                        .show(this);
                    final String openid = Cache.getCached(this, SDKConfig.KEY_OPENID);
                    String userInfo = Cache.getCached(this, SDKConfig.KEY_APPINFO);
                Gson gson = new Gson();
                final YiDengUserInfioBean yideng = gson.fromJson(userInfo, YiDengUserInfioBean.class);
                RegisterOptionalUserInfo registerOptionalUserInfo=new RegisterOptionalUserInfo();
                registerOptionalUserInfo.setNickname(yideng.getName());
                //注册为openID后5位
                JMessageClient.register("yideng"+openid.substring(openid.length()-6,openid.length()-1), openid, registerOptionalUserInfo, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        switch (i){
                            case 0:
                                JMessageClient.login("yideng"+openid.substring(openid.length()-6,openid.length()-1), openid, new BasicCallback() {
                                    @Override
                                    public void gotResult(int i, String s) {
                                        if(i==0){
                                            //提交头像
                                            commityidengUserIcon(yideng.getAvatar());
                                        }
                                    }
                                });
                                break;
                            case 898001:
                                JMessageClient.login("yideng"+openid.substring(openid.length()-6,openid.length()-1), openid, new BasicCallback() {
                                    @Override
                                    public void gotResult(int i, String s) {
                                        if(i==0){
                                            LemonBubble.hide();
                                            startActivity(new Intent(LoginActvity.this, MainActivity.class));
                                            TastyToast.makeText(getApplicationContext(), "登录成功", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                                        }
                                    }
                                });
                                break;
                        }
                    }

                });
                break;
            case SDKConfig.LOGINFAIL:
                TastyToast.makeText(getApplicationContext(), "登录失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
                break;
            default:
                TastyToast.makeText(getApplicationContext(), "登录失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
                break;
        }
    }

    private void commityidengUserIcon(final String url) {
        Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(final ObservableEmitter<File> e) throws Exception {
                RequestParams requestParams = new RequestParams(url);
                requestParams.setSaveFilePath(getCacheDir().getAbsolutePath()+"yitemp.jpg");
                x.http().get(requestParams, new Callback.CommonCallback<File>() {
                    @Override
                    public void onSuccess(File result) {
                        e.onNext(result);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(final File file) throws Exception {
                        JMessageClient.updateUserAvatar(file, new BasicCallback() {
                            @Override
                            public void gotResult(int i, String s) {
                                if(i==0){
                                    LemonBubble.hide();
                                    startActivity(new Intent(LoginActvity.this, MainActivity.class));
                                    TastyToast.makeText(getApplicationContext(), "登录成功", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                                    file.delete();
                                }
                            }
                        });
                    }
                });
    }

    @OnClick({R.id.loginactivity_Button_login, R.id.loginactivity_TextVieww_regist,R.id.loginactivity_ImageView_yideng,R.id.loginactivity_ImageView_qq})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginactivity_Button_login:
                final String username = mMaterialEditText_username.getText().toString().trim();
                final String userpass = mMaterialEditText_userpass.getText().toString().trim();
                JMessageClient.login(username, userpass, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if (i == 0) {
                            TastyToast.makeText(getApplicationContext(), "登录成功!", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                            startActivity(new Intent(LoginActvity.this, MainActivity.class));
                            //存储用户名和密码
                            SPUtil.putValue(getApplicationContext(), SPUtil.LOGIN_USERNAME, SPUtil.SPUtil_STRING, username);
                            SPUtil.putValue(getApplicationContext(), SPUtil.LOGIN_PASSWOED, SPUtil.SPUtil_STRING, userpass);
                        }else {
                            TastyToast.makeText(getApplicationContext(), "登录失败!", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                        }
                    }
                });
                break;
            case R.id.loginactivity_TextVieww_regist:
                startActivity(new Intent(LoginActvity.this, RegisteActivity.class));
                break;
            case R.id.loginactivity_ImageView_yideng:
                SuperID.faceLogin(this);
            case R.id.loginactivity_ImageView_qq:

                break;
        }
    }
}
